from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.modules.index import index_blu
# from info import redis_stock
from flask import render_template

from info.utils.common import user_login_data
from info.utils.response_code import RET


@index_blu.route("/news_list")
def get_news_list():
    """
    获取指定分类的新闻列表
    1.获取参数
    2.校验参数
    3.查询数据
    4.返回数据
    :return:
    """
    # 1.获取参数
    args_dict = request.args
    cid = args_dict.get("cid", "1")
    page = args_dict.get("page", "1")
    per_page = args_dict.get("per_page", constants.HOME_PAGE_MAX_NEWS)

    # 2.校验参数
    try:
        page = int(page)
        per_page = int(per_page)
        cid = int(cid)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 查询数据并且分页
    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)
    # print(cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        items = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    news_dict_li = []
    for news in items:
        news_dict_li.append(news.to_basic_dict())
    data = {
        "cid": cid,
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@index_blu.route("/")
@user_login_data
def index():

    # 获取新闻分类数据
    categories = Category.query.all()
    # print(categories)
    # 定义列表保存分类的数据
    categories_list = []
    # 遍历查询到的对象列表，调用对象的转换方法，把数据存到创建的列表中

    for category in categories:
        categories_list.append(category.to_dict())
        print(category.name)

    # 获取点击排行数据
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 创建一个空列表，把查询出来的列表进行便利并且把基本说明添加到列表中
    rank_news_list = []
    for news in news_list if news_list else []:
        rank_news_list.append(news.to_basic_dict())

    # 获取当前用户id
    user = g.user

    # 把之前查询到的用户状态封装到字典中，，将查询到的新闻排行列表也放入到字典中一并传到模板中
    data = {
        # 把之前查询到的用户状态封装到字典中
        "user_info": user.to_dict() if user else None,
        # 将查询到的新闻排行列表也放入到字典中
        "rank_news_list": rank_news_list,
        # 将查询到的分类数据放入到字典里传到模板
        "categories_list": categories_list
    }
    return render_template("news/index.html", data=data)


@index_blu.route("/favicon.ico")
def favicon():
    return current_app.send_static_file("news/favicon.ico")